<template>
  <div>
    <router-view>
      <div class="box" v-if="status">
        <div class="header">
          <div class="left">
            <el-input style="width: 120px; margin: 10px" v-model="Visitvalue" @input="searchDepart" placeholder="输入姓名" />
            <el-date-picker style="margin: 10px; width: 240px" v-model="value" @change="searchDepart" type="daterange" range-separator="到"
              start-placeholder="开始时间" end-placeholder="结束时间" size="default" />
            <!-- <el-button style="margin: 10px" size="small" type="primary" @click="searchDepart()">搜索</el-button> -->
          </div>
          <div class="right">
            <el-button style="margin: 10px" type="danger" @click="deleteBatches">批量删除</el-button>
          </div>
        </div>
        <el-table v-loading="loading" ref="table" :data="pageData" style="width: 100%; margin-bottom: 20px" row-key="id"
          stripe="true" :cell-style="{ textAlign: 'center' }" :header-cell-style="{ 'text-align': 'center' }"
          max-height="68vh">
          <el-table-column type="selection" width="55" fixed="left" />
          <el-table-column prop="nickname" label="姓名" width="120" fixed="left" />
          <el-table-column prop="card" label="就诊卡号" width="200" />
          <el-table-column prop="code" label="身份证号" width="250" />
          <el-table-column prop="tel" label="手机号" width="150" />
          <el-table-column prop="sex" label="性别" width="120">
            <template #default="scope">
              <div>{{ scope.row.sex == 1 ? '男' : '女' }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="地址" width="250" />
          <el-table-column prop="hos_status" label="是否启用" width="80">
            <template #default="scope">
              <el-switch :value="scope.row.hos_status === 1" @change="affirmSwitch(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column prop="money" label="余额" width="100" />
          <el-table-column prop="create_time" label="创建时间" width="100" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <div style="width: 100%; display: flex; justify-content: space-around">
                <!-- <el-icon color="#409EFC" :size="20" class="no-inherit" style="cursor: pointer"
                  ><Document @click="handleEdit(scope.$index, scope.row)"
                /></el-icon> -->
                <el-button type="danger" plain size="small" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div style="display: flex; justify-content: center">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30]"
            background="true" layout="total, sizes,->, prev, pager, next, jumper" :total="listNum"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
      <!-- 详情 -->
      <!-- <div v-else>
        <div class="box">
          <div class="box_top">
            <div class="box_top_word">患者信息</div>
            <el-button @click="cancel(ruleFormRef)">返回</el-button>
          </div>
          <div class="box_content">
            <div class="content">
              <div class="content_item">
                <div class="item_name">患者姓名</div>
                <div class="item_message">{{ form.nickname }}</div>
              </div>
              <div class="content_item">
                <div class="item_name">证件类型</div>
                <div class="item_message">身份证号</div>
              </div>
              <div class="content_item">
                <div class="item_name">就诊人地址</div>
                <div class="item_message">{{ form.address }}</div>
              </div>
              <div class="content_item">
                <div class="item_name">性别</div>
                <div class="item_message">{{ form.sex == 1 ? '男' : '女' }}</div>
              </div>
            </div>
            <div class="content">
              <div class="content_item">
                <div class="item_name">证件号码</div>
                <div class="item_message">{{ form.code }}</div>
              </div>
              <div class="content_item">
                <div class="item_name">手机号</div>
                <div class="item_message">{{ form.tel }}</div>
              </div>
            </div>
            <div class="content">
              <div class="content_item">
                <div class="item_name">照片</div>
                <div class="item_message"></div>
              </div>
              <div class="content_item">
                <div class="item_name">关系</div>
                <div class="item_message">{{ form.relationship }}</div>
              </div>
            </div>
          </div>
        </div>
      </div> -->
    </router-view>
  </div>
</template>

<script setup>
import { ref, watchEffect, onMounted, reactive } from 'vue';
import { addVisit, visit, deleteVisit } from '../../api/visit';
import { Plus, Delete, Edit, Document } from '@element-plus/icons-vue';

const form = reactive({
  nickname: '',
  address: '',
  sex: '',
  code: '',
  tel: '',
  relationship: '',
});
// UEditor配置
const editorConfig = reactive({
  UEDITOR_HOME_URL: '/UEditor/', // 访问 UEditor 静态资源的根路径，可参考常见问题1
});
const dialogFormVisible = ref(false); //弹窗状态
const url = ref('https://lxt.jingyi.icu/'); //域名头
const listNum = ref(0); //列表总数
const currentPage = ref(1); //当前页码数
const classcurrentPage = ref(1); //当前页码数
const pageSize = ref(10); //当前每页显示数量
const classpageSize = ref(10); //当前每页显示数量
const loading = ref(true); //加载状态
const ruleFormRef = ref(); //页面表单实例
const status = ref(true); //编辑添加页的显示隐藏状态
const table = ref(); //表格实例
const VisitList = ref([]); //动态列表
const classList = ref([]); //动态列表
const Visitvalue = ref(''); //搜索框内容
const searchData = ref([]); //搜索后列表
const value = ref('');
// 图片上传
const handleAvatarSuccess = (response, uploadFile) => {
  console.log(response);
  console.log(uploadFile);
  form.img = response.data.url;
};
const uploadError = (error, uploadFile) => {
  console.log(error);
  console.log(uploadFile);
  form.img = response.data.url;
};
// 表单效验
const rules = reactive({
  img: [
    {
      required: true,
      message: '请上传图片',
      trigger: 'change',
    },
  ],
  title: [
    {
      required: true,
      message: '请输入动态名称',
      trigger: 'change',
    },
  ],
  details: [
    {
      required: true,
      message: '请输入动态详情',
      trigger: 'change',
    },
  ],
});
//分页数据显示
const pageData = computed(() => {
  console.log();
  let a = [];
  for (
    let i = (currentPage.value - 1) * pageSize.value;
    i < currentPage.value * pageSize.value;
    i++
  ) {
    if (searchData.value[i]) {
      a.push(searchData.value[i]);
    }
  }
  console.log(a);
  return a;
});
//分类列表分页数据显示
const classpageData = computed(() => {
  console.log();
  let a = [];
  for (
    let i = (classcurrentPage.value - 1) * classpageSize.value;
    i < classcurrentPage.value * classpageSize.value;
    i++
  ) {
    if (classList.value[i]) {
      a.push(classList.value[i]);
    }
  }
  console.log(a);
  return a;
});
// 搜索
const searchDepart = () => {
  console.log(value.value);
  searchData.value = VisitList.value.filter(function (item) {
    let date = new Date(item.create_time).getTime();
    if (value.value) {
      let star = new Date(value.value[0]).getTime();
      let end = new Date(value.value[1]).getTime();
      if (date > star && date < end && item.title.indexOf(Visitvalue.value) > -1) {
        return item;
      }
    } else {
      if (item.nickname.indexOf(Visitvalue.value) > -1) {
        return item;
      }
    }
  });
  listNum.value = searchData.value.length;
};
// 请求列表
const requestList = async () => {
  try {
    const res = await visit();
    console.log('动态列表', res);
    VisitList.value = res.data;
    searchDepart();
    loading.value = false;
    console.log('初次列表', searchData.value);
  } catch (error) {
    console.error(error);
  }
};
requestList();
// 每页显示数量改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  console.log(`${val} items per page`);
};
// 页码数改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  console.log(`current page: ${val}`);
};
// 分类页码数改变
const classhandleCurrentChange = (val) => {
  classcurrentPage.value = val;
  console.log(`current page: ${val}`);
};
// 编辑
const handleEdit = (index, row) => {
  status.value = false;
  form.nickname = row.nickname;
  form.address = row.address;
  form.sex = row.sex;
  form.code = row.code;
  form.tel = row.tel;
  form.relationship = row.relationship;
  console.log(form);
  console.log(index, row);
};
// 删除
const handleDelete = (index, row) => {
  console.log(index, row);
  ElMessageBox.confirm('是否确认删除?', '删除动态', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then((res) => {
      console.log(res);

      deleteVisit({
        id: row.id,
      }).then((result) => {
        console.log(result);
        if (result.code == 0) {
          ElMessage({
            type: 'danger',
            message: result.msg,
          });
        } else if (result.code == 1) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          });
          requestList();
        }
      });
    })
    .catch((res) => {
      console.log(res);
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
};
// 批量删除
// const deleteBatches = () => {
//   ElMessageBox.confirm('是否确认删除?', '删除动态', {
//     confirmButtonText: '确认',
//     cancelButtonText: '取消',
//     type: 'warning',
//   })
//     .then((res) => {
     
//     })
//     .catch((res) => {
//       console.log(res);
//       ElMessage({
//         type: 'info',
//         message: '取消删除',
//       });
//     });
// };
const deleteBatches = () => {
  let selectedRows = table.value.getSelectionRows();
  if (selectedRows.length === 0) {
    ElMessage({
      type: 'warning',
      message: '暂无选中数据',
    });
  } else {
    ElMessageBox.confirm('是否确认删除?', '删除动态', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then((res) => {
        console.log(res);
      let arr = table.value.getSelectionRows();
      let arrs = [];
      console.log(arr);
      // 构造一个 Promise 数组，每个 Promise 表示一条记录的删除操作
      const promises = arr.map((element) => {
        return deleteVisit({ id: element.id });
      });
      // 使用 Promise.all() 处理 Promise 数组，一旦其中有一个Promise被拒绝（即删除失败），就会执行catch()方法，
      // 否则，如果所有的Promise都得到了解决（即删除成功），就会执行then()方法。
      Promise.all(promises)
        .then((results) => {
          console.log(results);
          results.forEach((result) => {
            if (result.code == 0) {
              ElMessage({
                type: 'danger',
                message: result.msg,
              });
            } else if (result.code == 1) {
              arrs.push(result.data);
            }
          });
          if (arrs.length == arr.length) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            });
          } else {
            ElMessage({
              type: 'warning',
              message: '删除失败，请重试',
            });
          }
          requestList();
        })
        .catch((error) => {
          console.log(error);
          ElMessage({
            type: 'warning',
            message: '删除失败，请重试',
          });
        });
      })
      .catch((res) => {
        console.log(res);
        ElMessage({
          type: 'info',
          message: '取消删除',
        });
      });
  }
};
// 清空表单
const clearForm = () => {
  form.nickname = '';
  form.address = '';
  form.sex = '';
  form.code = '';
  form.tel = '';
  form.relationship = '';
};
// 取消
const cancel = (formEl) => {
  clearForm();
  status.value = true;
};

// 列表状态编辑
const affirmSwitch = (data) => {
  console.log(data.hos_status);
  if (data.hos_status == 1) {
    data.hos_status = 2;
  } else {
    data.hos_status = 1;
  }
  console.log(data);
  addVisit(data).then((res) => {
    console.log(res);
    if (res.code == 0) {
      ElMessage({
        type: 'danger',
        message: '状态更改失败',
      });
    } else {
      ElMessage({
        type: 'success',
        message: '状态更改成功',
      });
    }

    requestList();
  });
};
</script>

<style lang="scss" scoped>
.box {
  width: 100%;
  background-color: rgb(255, 255, 255);
  overflow-y: scroll;
}

.left {
  max-width: 650px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.right {
  max-width: 300px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
}

.header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
}

.head_word {
  width: 100%;
  padding: 10px 20px;
  border-bottom: 1px solid #e5e5e5;
  margin-bottom: 20px;
  color: #427eff;
}

.window {
  width: 100%;
  overflow-x: scroll;
  padding: 10px;
  background-color: white;
}

.hint {
  margin-left: 10px;
  color: #a6a6a6;
  font-size: 14px;
}

.head_img {
  // width: 40px;
  height: 40px;
  // border-radius: 40px;
}

.lable {
  width: 100%;
  line-height: 1;
  border-radius: 50px;
  padding: 10px;
}

.list_word {
  width: 100%;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.inpuut_box {
  width: 800px;
  display: flex;
  flex-wrap: wrap;
}

.box_top {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #e5e5e5;
}

.box_top_word {
  color: #0079ff;
}

.box_content {
  display: flex;
  overflow-x: scroll;
  padding: 0 50px;
}

.content {
  min-width: 350px;
  width: 33%;
  display: flex;
  flex-wrap: wrap;
  padding: 10px 0;
}

.content_item {
  width: 100%;
  display: flex;
  margin: 20px 0;
}

.item_name {
  width: 150px;
  color: #acacac;
}

.item_message {
  color: #505050;
}

.box_bottom {
  width: 800px;
}
</style>
